package com.atguigu.spzx.cart.service.impl;

import com.atguigu.spzx.cart.service.CartService;

import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.common.exception.SpzxException;
import com.atguigu.spzx.common.interceptor.SpzxUserInfoInterceptor;
import com.atguigu.spzx.model.entity.h5.CartItem;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.product.client.ProductClient;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class CartServiceImpl implements CartService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    ProductClient productClient;
    @Override
    public void add2Cart(Long skuId, Integer skuNum) {
        //1、获取用户的购物车：
        Long userId = SpzxUserInfoInterceptor.THREAD_LOCAL.get().getId();
        //ops和Map结构的操作类似
        BoundHashOperations ops = redisTemplate.boundHashOps("cart:" + userId);
        //2、判断用户购物车中是否存在skuId的购物项
        Boolean hasKey = ops.hasKey(String.valueOf(skuId));
        CartItem cartItem = null;
        if(hasKey){
            //如果存在：获取购物项更新数量
            cartItem = (CartItem) ops.get(String.valueOf(skuId));
            cartItem.setSkuNum(cartItem.getSkuNum()+skuNum);
            cartItem.setUpdateTime(new Date());
            //更新到购物车中
        }else{
            //如果不存在：新创建购物项添加到购物车中 初始数量为skuNum
            cartItem = new CartItem();
            cartItem.setSkuId(skuId);
            //默认选中
            cartItem.setIsChecked(1);
            //根绝skuId查询sku表的数据
            //远程调用查询数据
            Result<ProductSku> result = productClient.findSkuById(skuId);
            if(result.getCode()!=200){
                throw new SpzxException(ResultCodeEnum.ERROR , null);
            }
            ProductSku productSku = result.getData();
            cartItem.setImgUrl(productSku.getThumbImg());
            cartItem.setSkuName(productSku.getSkuName());
            cartItem.setCartPrice(productSku.getSalePrice());

            cartItem.setSkuNum(skuNum);
            cartItem.setCreateTime(new Date());
            cartItem.setUpdateTime(new Date());
            cartItem.setUserId(userId);

        }
        ops.put(String.valueOf(skuId) , cartItem);

    }

    @Override
    public List<CartItem> cartList() {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();

        if(ops.size()==0){
            return null;
        }
        //获取hash结构的values集合返回
        return ops.values();
    }

    private BoundHashOperations<String, String, CartItem> getUserCart() {
        Long userId = SpzxUserInfoInterceptor.THREAD_LOCAL.get().getId();
        BoundHashOperations<String,String,CartItem> ops = redisTemplate.boundHashOps("cart:" + userId);
        return ops;
    }

    @Override
    public void deleteCart(Long skuId) {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();
        //删除购物项
        ops.delete(String.valueOf(skuId));

    }

    @Override
    public void checkCart(Long skuId, Integer status) {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();
        CartItem cartItem = ops.get(String.valueOf(skuId));
        cartItem.setIsChecked(status);
        //更新到购物车中
        ops.put(String.valueOf(skuId),cartItem);
    }

    @Override
    public void allCheckCart(Integer status) {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();
        //对hash的键和值 键值对进行遍历
        ops.entries().forEach((skuIdStr , cartItem)->{
            cartItem.setIsChecked(status);
            ops.put(skuIdStr , cartItem);
        });
    }

    @Override
    public void clearCart() {
        Long userId = SpzxUserInfoInterceptor.THREAD_LOCAL.get().getId();
        redisTemplate.delete("cart:"+userId);
    }

    @Override
    public List<CartItem> findCheckedCartItems() {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();
        if(ops.size()==0){
            return null;
        }
//        ops.keys()  获取键的set集合
//        ops.values() 获取值的list集合
        return ops.values().stream()
                //过滤选中的购物项列表
                .filter(cartItem -> cartItem.getIsChecked()==1)
                .collect(Collectors.toList());
    }

    @Override
    public void deleteCartItems() {
        BoundHashOperations<String, String, CartItem> ops = getUserCart();
        //删除购物车中选中的购物项：
        ops.entries().forEach((k,v)->{
            if(v.getIsChecked()==1){
                ops.delete(k);
            }
        });

    }
}
